Research
Security News
Threat Actor Exposes Playbook for Exploiting npm to Build Blockchain-Powered Botnets
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
module-alias
Advanced tools
The module-alias package is used to create aliases of directory paths, allowing you to simplify the require/import statements in your Node.js projects. This can be particularly useful for projects with deep directory structures, making the code cleaner and easier to maintain.
Registering Aliases
This feature allows you to register aliases for directories so that you can require modules using the alias instead of relative paths.
require('module-alias/register');
moduleAlias.addAliases({
'@root' : __dirname,
'@models' : __dirname + '/models',
'@controllers': __dirname + '/controllers',
'@lib' : __dirname + '/lib'
});
Customizing Aliases with package.json
You can also define aliases directly in your package.json file, which module-alias will read and use to resolve modules.
{
"_moduleAliases": {
"@root": ".",
"@models": "./models",
"@controllers": "./controllers",
"@lib": "./lib"
}
}
Requiring Modules with Aliases
Once aliases are set up, you can require modules using the defined aliases, making the require statements much cleaner and easier to understand.
const User = require('@models/user');
This package allows you to alias module paths in Node.js, similar to module-alias. It provides a way to keep your require calls clean. However, it is not as widely used or as well-maintained as module-alias.
This Babel plugin allows you to add new 'root' directories that contain your modules. It also lets you map a module to another module or filepath. It is more flexible than module-alias as it integrates with Babel and supports both Node.js and frontend JavaScript projects.
This package provides similar functionality to module-alias, allowing you to define aliases for your modules and directories. It differs in the way it sets up the aliases, using symbolic links, which can be more compatible with certain tools that do not understand module resolution.
If everyone who reads this would donate just $1, I would be a millionaire in 1 week! 🙃 Thank you for reaching 1M+ weekly downloads!
More donations means more motivation for me to make updates. Thank you so much!
Create aliases of directories and register custom module paths in NodeJS like a boss!
No more shit-coding paths in Node like so:
require('../../../../some/very/deep/module')
Enough of this madness!
Just create an alias and do it the right way:
var module = require('@deep/module')
// Or ES6
import module from '@deep/module'
It also allows you to register directories that will act just like node_modules
but with your own private modules, so that you can access them directly:
require('my_private_module');
// Or ES6
import module from 'my_private_module'
WARNING: If you are going to use this package within another NPM package, please read Using within another NPM package first to be aware of potential caveats.
npm i --save module-alias
Add your custom configuration to your package.json
(in your application's root)
// Aliases
"_moduleAliases": {
"@root" : ".", // Application's root
"@deep" : "src/some/very/deep/directory/or/file",
"@my_module" : "lib/some-file.js",
"something" : "src/foo", // Or without @. Actually, it could be any string
}
// Custom module directories, just like `node_modules` but with your private modules (optional)
"_moduleDirectories": ["node_modules_custom"],
Then add this line at the very main file of your app, before any code
require('module-alias/register')
And you're all set! Now you can do stuff like:
require('something')
const module = require('@root/some-module')
const veryDeepModule = require('@deep/my-module')
const customModule = require('my_private_module') // module from `node_modules_custom` directory
// Or ES6
import 'something'
import module from '@root/some-module'
import veryDeepModule from '@deep/my-module'
import customModule from 'my_private_module' // module from `node_modules_custom` directory
If you don't want to modify your package.json
or you just prefer to set it all up programmatically, then the following methods are available for you:
addAlias('alias', 'target_path')
- register a single aliasaddAliases({ 'alias': 'target_path', ... })
- register multiple aliasesaddPath(path)
- Register custom modules directory (like node_modules, but with your own modules)Examples:
const moduleAlias = require('module-alias')
//
// Register alias
//
moduleAlias.addAlias('@client', __dirname + '/src/client')
// Or multiple aliases
moduleAlias.addAliases({
'@root' : __dirname,
'@client': __dirname + '/src/client',
...
})
// Custom handler function (starting from v2.1)
moduleAlias.addAlias('@src', (fromPath, request, alias) => {
// fromPath - Full path of the file from which `require` was called
// request - The path (first argument) that was passed into `require`
// alias - The same alias that was passed as first argument to `addAlias` (`@src` in this case)
// Return any custom target path for the `@src` alias depending on arguments
if (fromPath.startsWith(__dirname + '/others')) return __dirname + '/others'
return __dirname + '/src'
})
//
// Register custom modules directory
//
moduleAlias.addPath(__dirname + '/node_modules_custom')
moduleAlias.addPath(__dirname + '/src')
//
// Import settings from a specific package.json
//
moduleAlias(__dirname + '/package.json')
// Or let module-alias to figure where your package.json is
// located. By default it will look in the same directory
// where you have your node_modules (application's root)
moduleAlias()
Luckily, WebPack has a built in support for aliases and custom modules directories so it's easy to make it work on the client side as well!
// webpack.config.js
const npm_package = require('./package.json')
module.exports = {
entry: { ... },
resolve: {
root: __dirname,
alias: npm_package._moduleAliases || {},
modules: npm_package._moduleDirectories || [] // eg: ["node_modules", "node_modules_custom", "src"]
}
}
More details on the official documentation.
Unfortunately, module-alias
itself would not work from Jest due to a custom behavior of Jest's require
. But you can use it's own aliasing mechanism instead. The configuration can be defined either in package.json
or jest.config.js
. The example below is for package.json
:
"jest": {
"moduleNameMapper": {
"@root/(.*)": "<rootDir>/$1",
"@client/(.*)": "<rootDir>/src/client/$1"
},
}
More details on the official documentation.
You can use module-alias
within another NPM package, however there are a few things to take into consideration.
require('module-alias/register')
for automatic detection of package.json
location (where you defined your aliases), as it tries to find package.json in either the current working directory of your node process, or two levels down from node_modules/module-alias. It is extremely likely that this is end-user code. So, instead, your should either register aliases manually with moduleAlias.addAlias
, or using something like require('module-alias')(__dirname)
.Here is an example project.
This module does not play well with:
In order to register an alias it modifies the internal Module._resolveFilename
method so that when you use require
or import
it first checks whether the given string starts with one of the registered aliases, if so, it replaces the alias in the string with the target path of the alias.
In order to register a custom modules path (addPath
) it modifies the internal Module._nodeModulePaths
method so that the given directory then acts like it's the node_modules
directory.
If you are using this on an existing project, you can use relative-to-alias to refactor your code to start using aliases.
If everyone who downloads module-alias would donate just $1, I would be a millionaire in 1 week!
I love contributing to open source, for free, but you know, sometimes, in the middle of the night, I may wan to eat.
There are some improvements planned for module-alias and your donations will help a lot to make it happen faster.
DONATE $1 ❤️ and thank you so much!
FAQs
Create aliases of directories and register custom module paths
The npm package module-alias receives a total of 230,660 weekly downloads. As such, module-alias popularity was classified as popular.
We found that module-alias demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
Security News
NVD’s backlog surpasses 20,000 CVEs as analysis slows and NIST announces new system updates to address ongoing delays.
Security News
Research
A malicious npm package disguised as a WhatsApp client is exploiting authentication flows with a remote kill switch to exfiltrate data and destroy files.